package com.atguigu.crowd.service.impl;

import com.atguigu.crowd.constant.CrowdConstant;
import com.atguigu.crowd.exception.LoginAcctAlreadyInForUpdateUseException;
import com.atguigu.crowd.exception.LoginAcctAlreadyInUseException;
import com.atguigu.crowd.exception.LoginFailedException;
import com.atguigu.crowd.mapper.AdminMapper;
import com.atguigu.crowd.service.api.AdminService;
import com.atguigu.crowd.util.CrowdUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import entity.Admin;
import entity.AdminExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
   private BCryptPasswordEncoder passwordEncoder;

//    @Override
//    public void saveAdmmin(Admin admin) {
//        adminMapper.insert(admin);
//
//    }

    @Override
    public List<Admin> getAll() {
        return adminMapper.selectByExample(new AdminExample());
    }

    @Override
    public Admin getAdminByLoginAcct(String loginAcct, String userPswd) {
        // 1.根据登陆账号查询Admin对象
        //  ①创建 AdminExample 对象
        AdminExample adminExample = new AdminExample();
        // ②.创建Criteria对象
        AdminExample.Criteria criteria = adminExample.createCriteria();
        // ③.调用adminMapper的方法来查询
        criteria.andLoginAcctEqualTo(loginAcct);
        List<Admin> adminList = adminMapper.selectByExample(adminExample);

        // ④.判断admin对象是否是null或者数据库不正常
        // 2.判断 Admin 对象是否为 null
        if (adminList == null || adminList.size() == 0) {
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }
//        System.out.println("adminList.size：" + adminList.size());
        if (adminList.size() > 1) {
            throw new RuntimeException(CrowdConstant.MESSAGE_SYSTEM_ERROR_LOGIN_NOT_UNIQUE);
        }
        Admin admin = adminList.get(0);
        // 3.如果admin对象返回是null那么抛出异常
        if (admin == null) {
            throw new RuntimeException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }
        // 4.如果 Admin 对象不为 null 则将数据库密码从 Admin 对象中取出
        String userPswdDB = admin.getUserPswd();
//        System.out.println("数据库中的密码:"+userPswdDB);
        // 5.将表单提交的明文密码进行加密
        String userPwdForm = CrowdUtil.md5(userPswd);
//        System.out.println("表单中的密码:"+userPwdForm);
        // 6.对密码进行比较
        if (!Objects.equals(userPwdForm, userPswdDB)) {
            // 7.如果比较结果是不一致则抛出异常
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }
        // 8.如果一致则返回 Admin 对象
        return admin;
    }

    @Override
    public Admin getAdminByLoginAcct(String loginAcct) {
        AdminExample example = new AdminExample();
        AdminExample.Criteria criteria = example.createCriteria();
        criteria.andLoginAcctEqualTo(loginAcct);
        List<Admin> admins = adminMapper.selectByExample(example);
        Admin admin = admins.get(0);
        return admin;
    }

    @Override
    public PageInfo<Admin> getPageInfo(String keyword, Integer pageNum, Integer pageSize) {
        // 利用PageHelper的静态方法开启分页
        PageHelper.startPage(pageNum, pageSize);

        // 调用Mapper接口的对应方法
        List<Admin> list = adminMapper.selectAdminByKeyword(keyword);

//        // 为了方便页面的使用，把Admin的List封装成PageInfo（放别得到页码等数据）
//        PageInfo<Admin> pageInfo = new PageInfo<>(list);

        // 返回得到的pageInfo对象
        return new PageInfo<>(list);
    }

    @Override
    public void remove(Integer adminId) {
        adminMapper.deleteByPrimaryKey(adminId);
    }

    @Override
    public void saveAdmin(Admin admin) {
        String userPswd = admin.getUserPswd();
//        userPswd = CrowdUtil.md5(userPswd);
        userPswd = passwordEncoder.encode(userPswd);
        admin.setUserPswd(userPswd);
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
        String createTime = simpleDateFormat.format(date);
        admin.setCreateTime(createTime);
        try {
            adminMapper.insert(admin);
        } catch (Exception e) {
            e.printStackTrace();
            // 这里出现异常的话一般就是DuplicateKeyException（因为插入的loginAcct已存在而触发）
            if(e instanceof DuplicateKeyException){
//                // 如果确实是DuplicateKeyException，此时抛出一个自定义的异常
                throw new LoginAcctAlreadyInUseException(CrowdConstant.MESSAGE_SYSTEM_ERROR_LOGIN_NOT_UNIQUE);
            }
        }
    }

    @Override
    public void saveAdminRoleRelationship(Integer adminId, List<Integer> roleIdList) {

        // 先清除旧的对应inner_admin_role表中对应admin_id的数据
        adminMapper.clearOldRelationship(adminId);

        // 如果roleIdList非空，则将该list保存到数据库表中，且admin_id=adminId
        if (roleIdList != null && roleIdList.size() > 0){
            adminMapper.saveAdminRoleRelationship(adminId,roleIdList);
        }
        // roleIdList为空，则清空后不做操作
    }

    @Override
    public Admin getAdminById(Integer adminId) {
return adminMapper.selectByPrimaryKey(adminId);
    }

    @Override
    public void updateAdmin(Admin admin) {
        try {
            adminMapper.updateByPrimaryKeySelective(admin);
        } catch (Exception e) {
            e.printStackTrace();
            if(e instanceof DuplicateKeyException){
//                // 如果确实是DuplicateKeyException，此时抛出一个自定义的异常
                throw new LoginAcctAlreadyInForUpdateUseException(CrowdConstant.MESSAGE_SYSTEM_ERROR_LOGIN_NOT_UNIQUE);
            }
        }
    }
}
